<script setup lang="ts">
import { Form, FormSchema } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { PropType, reactive, watch } from 'vue'
import { DepartmentUserItem } from '@/api/department/types'
import { useValidator } from '@/hooks/web/useValidator'
import { string } from 'vue-types'

const { required } = useValidator()

const props = defineProps({
  currentRow: {
    type: Object as PropType<DepartmentUserItem>,
    default: () => undefined
  },
  formSchema: {
    type: Array as PropType<FormSchema[]>,
    default: () => []
  },
  actionType: {
    type: string,
    default: () => []
  }
})

const rules = reactive({
  realname: [required()],
  username: [required()],
  orgCode: [required()],
  roles: [required()],
  status: [required()]
})

const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose, setSchema } = formMethods

const submit = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log(err)
  })
  if (valid) {
    const formData = await getFormData()
    return formData
  }
}

const disabledUserName = () => {
  if (props.actionType === 'edit') {
    // 修改时禁用用户名
    setSchema([
      {
        field: 'username',
        path: 'componentProps.disabled',
        value: true
      }
    ])
  } else {
    setSchema([
      {
        field: 'username',
        path: 'componentProps.disabled',
        value: false
      }
    ])
  }
}
disabledUserName()

watch(
  () => props.currentRow,
  (currentRow) => {
    if (!currentRow) return
    setValues(currentRow)
  },
  {
    deep: true,
    immediate: true
  }
)

defineExpose({
  submit
})
</script>

<template>
  <Form :rules="rules" @register="formRegister" :schema="formSchema" />
</template>
